import os
import subprocess
import threading

def read_stream(stream, callback):
    with stream:
        for line in iter(stream.readline, ""):
            callback(line.strip())

def execute_scripts_in_order(scripts_with_args):
    for index, (script, args) in enumerate(scripts_with_args, start=1):
        if not os.path.isfile(script):
            print(f"Script not found: {script}")
            continue
        
        print(f"执行脚本 {index}/{len(scripts_with_args)}: {os.path.basename(script)}...")
        try:
            process = subprocess.Popen(
                ["python", script] + args,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
                encoding="utf-8"
            )

            stdout_thread = threading.Thread(
                target=read_stream,
                args=(process.stdout, lambda x: print(f"Output: {x}", flush=True))
            )
            stderr_thread = threading.Thread(
                target=read_stream,
                args=(process.stderr, lambda x: print(f"Error: {x}", flush=True))
            )

            stdout_thread.start()
            stderr_thread.start()

            stdout_thread.join()
            stderr_thread.join()

            process.wait()

            if process.returncode != 0:
                print(f"Script {script} failed with return code {process.returncode}")

        except Exception as e:
            print(f"Failed to execute {script}: {e}")

X_RANGE = (-45, 45)
Y_RANGE = (0, 90)
NUM_FRAMES = 16

GRID_SIZE = (90, 90)
NUM_HEIGHT_LAYERS = 8
NUM_PARAM = 4
Z_MIN = -1
Z_MAX = 3

if __name__ == "__main__":
    scripts_with_args = [
        (".\\script\\pre\\generate_label_ref.py",
         []),

        # (".\\script\\pre\\gernerate_input1.py",
        #  ["--X_RANGE", str(X_RANGE),
        #   "--Y_RANGE", str(Y_RANGE),
        #   "--NUM_FRAMES", str(NUM_FRAMES)]),

        # (".\\script\\pre\\gernerate_input2.py",
        #  ["--X_RANGE", str(X_RANGE),
        #   "--Y_RANGE", str(Y_RANGE),
        #   "--NUM_FRAMES", str(NUM_FRAMES),
        #   "--GRID_SIZE", str(GRID_SIZE),
        #   "--NUM_HEIGHT_LAYERS", str(NUM_HEIGHT_LAYERS),
        #   "--NUM_PARAM", str(NUM_PARAM),
        #   "--Z_MIN", str(Z_MIN),
        #   "--Z_MAX", str(Z_MAX)]),
    ]

    if os.path.exists("./workspace/image/SAR/label.json"):
        scripts_with_args = [
            (".\\script\\pre\\generate_label.py",
             ["--X_RANGE", str(X_RANGE),
              "--Y_RANGE", str(Y_RANGE)]),

            (".\\script\\pre\\gernerate_show.py",
             ["--X_RANGE", str(X_RANGE),
              "--Y_RANGE", str(Y_RANGE)]),
        ]

    execute_scripts_in_order(scripts_with_args)
